# 共用的自定义工具类
import functools

from flask import session, current_app, g

# 自定义过滤器，过滤点击排序html的class
def do_index_class(index):
    if index == 1:
        return "first"
    elif index == 2:
        return "second"
    elif index == 3:
        return "third"
    else:
        return ""


# # 装饰器示例:使用functools.wraps去装饰内层函数.可以保持当前装饰器去装饰的函数__name__值不变
# import functools
#
#
# def user_login_data(f):
#     @functools.wraps(f)  # 注释掉此行,以下打印结果均为wrapper;否则为num1,num2
#     def wrapper(*args, **kwargs):
#         return f(*args, **kwargs)
#
#     return wrapper
#
#
# # @app.route('/news/<int:news_id>')
# @user_login_data
# def num1():
#     print('aaa')
#
#
# # @app.route('/')
# @user_login_data
# def num2():
#     print('bbb')
#
#
# if __name__ == "__main__":
#     print(num1.__name__)
#     print(num2.__name__)


def user_login_data(f):
    # 使用functools.wraps去装饰内层函数.可以保持当前装饰器去装饰的函数__name__值不变
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        # 获取到当前登录用户的id
        user_id = session.get("user_id", None)
        # 通过id获取用户信息
        user = None
        if user_id:
            # 尝试查询用户模型
            try:
                from info.models import User
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)
        # 把查询出的数据赋值给g变量
        g.user = user
        return f(*args, **kwargs)
    return wrapper

# def query_user_data():
#     # 查询用户信息
#     user_id = session.get("user_id", None)
#     user = None
#     if user_id:
#         # 尝试查询用户模型
#         try:
#             user = User.query.get(user_id)
#         except Exception as e:
#             current_app.logger.error(e)
#     return None
